define(function(require, exports){
	var $ = require("jquery");
	var util = require('util');

	// 渲染模版
	var RENDER_TPL = {
		// 名称状态
		'name': `
			<div class="tl fl pd10 pt20 " title="{name}">
				<i class="status {status-icon} cur_p dib valign-m"></i>
				<span class="text-truncate w200 dib valign-m">
				{name}
				</span>
			</div>
		`,
		// 其他条件
		'other': `
			<div class="pd10 lh24">
				<div class="w250 dib">
					<div>自定义ID：{custome_id}</div>
					<div>投放速度：{speed}</div>
					<div class="text-truncate">曝光监测：{impression}</div>
					<div class="text-truncate">点击监测：{click}</div>
				</div>
				<div class="w250 dib valign-t">
					<div>品牌保护：{brand_safe}</div>
					<div>智能监控：{monitor}</div>
					<div>标签：{tag}</div>
				</div>
			</div>
		`,
		// 预算
		'budget': `
			<div class="pd10">
				<div title="{total_budget}">总预算：{total_budget}</div>
				<div title="{total_impression}">总展示：{total_impression}</div>
				<div title="{total_click}">总点击：{total_click}</div>

				<div class="mt15" title="{daily_budget}">每日预算：{daily_budget}</div>
				<div title="{daily_impression}">每日展示：{daily_impression}</div>
				<div title="{daily_click}">每日点击：{daily_click}</div>
			</div>
		`,
		// 出价
		/*
			price_type: 出价类型
			price: 出价
			price_title: 出价方式对应的key名称
			price_model: 算法类型
			price: 最高出价
			price_title: 最高出价方式对应的key名称
		*/
		'price': `
			<div class="pd10">
				<div title="{price_type}">出价方式：{price_type}</div>
				<div title="{price}">{price_label}：{price}{price_unit}</div>
				<div title="{optimize_mode}">算法模型：{optimize_mode}</div>
				<div title="{topCPM}" class="{topCPM_display}">最高CPM：{topCPM}</div>
			</div>
		`,

		'extra_price': `
			<div class="pd10">差异出价：{price}</div>
		`,

		// 创意包落地页
		'materialGroup': `
			<div class="pd10">
				<div>创意包 ({sweety_number})</div>
				<div>落地页 ({whisky_number})</div>
			</div>
		`,
		// 展示策略
		'optimizeStrategy': `
			<div class="pd10">
				<div>创意包：{sweety}</div>
				<div>落地页：{whisky}</div>
				<div>广告位：{spot}</div>
				<div>展示顺序：{impression}</div>
			</div>
		`,

		'special_condition': `
			<div class="pd10 lh25">
				<div>特殊条件 ({number})</div>
			</div>
		`,
		// 频次控制
		'frequency': `
			<div class="pd10">{type} {period} {frequency}次</div>
		`,
		// 条件
		'condition': `
			<div class="pd10" title="{title}">{desc}</div>
		`
	};
	exports.RENDER_TPL = RENDER_TPL;

	// 渲染方法
	var RENDER_FUNC = {
		// 名称
		'name': function(data)
		{
			data = data || {};
			var name = data.name;
			var status = data.status;

			var map = {
				'1': 'status-running',
				'2': 'status-pause'
			};
			var render_tpl = RENDER_TPL.name;
			return render_tpl.replace(/{name}/g, name)
					.replace(/{status-icon}/g, (map[status] || ''));
		},
		'budget': function(data)
		{
			data = data || {};
			var total = data.totalLimit || {};
			var daily = data.dailyLimit || {};

			var render_tpl = RENDER_TPL.budget;
			var price_unit = LANG('元');
			var impression_unit = LANG('千次');
			var click_unit = LANG('次');
			var def = LANG('不限');


			var total_budget		= total.Budget		? (total.Budget + LANG('元')) : def;
			var total_impression	= total.Impression	? (total.Impression + LANG('千次')): def;
			var total_click			= total.Click		? (total.Click + LANG('次')) : def;
			var daily_budget		= daily.Budget		? (daily.Budget + LANG('元')) : def;
			var daily_impression	= daily.Impression	? (daily.Impression + LANG('千次')) : def;
			var daily_click			= daily.Click		? (daily.Click + LANG('次')) : def;


			return render_tpl
						.replace(/{total_budget}/g,		total_budget)
						.replace(/{total_impression}/g,	total_impression)
						.replace(/{total_click}/g,		total_click)
						.replace(/{daily_budget}/g,		daily_budget)
						.replace(/{daily_impression}/g,	daily_impression)
						.replace(/{daily_click}/g,		daily_click);
		},
		'other': function(data)
		{
			data = data || {};
			var render_tpl = RENDER_TPL.other;

			// 监测
			var ThirdMonitor = data.ThirdMonitor || {};
			var impression = (ThirdMonitor.Exposure || []).join('\n');
			var click = (ThirdMonitor.Click || []).join('\n');
			
			var monitor_action = data.Monitor && data.Monitor.Action;
			var monitor_name = monitor_action ? LANG('开启监控') : LANG('关闭监控');
			var speed_name = data.GovernorStatus ? LANG('均匀投放') : LANG('尽快投放');
			var def = LANG('无');

			return render_tpl
						.replace(/{custome_id}/g, data.CustomId		|| def)
						.replace(/{brand_safe}/g, data.BrandSafeUrl	|| def)
						.replace(/{impression}/g, impression	|| def)
						.replace(/{click}/g, click	|| def)
						.replace(/{tag}/g, (data.Label || []).join(',') || def)
						.replace(/{speed}/g, speed_name)
						.replace(/{monitor}/g, monitor_name)
		},
		// 主条件的出价
		'price': function(data)
		{
			data = data || {};
			var render_tpl = RENDER_TPL.price;

			var optimize_mode_map = {
				'1': LANG('模型A'),
				'2': LANG('模型B')
			};
			var price_type_map = {
				'0': {name: LANG("竞价CPM"), unit: LANG('元/千次曝光'), label: LANG('目标CPM')},
				'1': {name: LANG("CPA优化"), unit: LANG('元'), label: LANG('目标CPA')},
				'2': {name: LANG("CPC优化"), unit: LANG('元'), label: LANG('目标CPC')},
				'3': {name: LANG("固定CPC"),unit: LANG('元'), label: LANG('结算CPC')}
			};

			// 类型
			var price_type = data.Way || 0;
			// 优化模型
			var optimize_mode = data.OptimizeMode || 1;

			var priceMap = price_type_map[price_type];
			// 是否现实最高cpm, 只有cpm同时模型A的时候显示
			var topCPM_display = 'dn';
			if ((price_type == 0) && (optimize_mode == 1))
			{
				topCPM_display = '';
			}

			// 默认值
			var ret = render_tpl;
			if (!data.Price)
			{
				ret = ret.replace(/{price}{price_unit}/, LANG('不限'));
			}

			ret = ret.replace(/{price_type}/g, priceMap.name)
					.replace(/{price_label}/g, priceMap.label)
					.replace(/{price}/g, data.Price)
					.replace(/{price_unit}/g, priceMap.unit)
					.replace(/{optimize_mode}/g, optimize_mode_map[optimize_mode])
					.replace(/{topCPM}/g, data.TopCpm || LANG('不限'))
					.replace(/{topCPM_display}/g, topCPM_display);


			return ret;
		},
		// 附加条件的差异出价
		'extra_price': function(data)
		{
			data = data || {}
			var render_tpl = RENDER_TPL.extra_price;

			var type_map ={
				'0': LANG('元'),
				'1': '%'
			}
			var type = type_map[data.Type];
			return render_tpl.replace(/{price}/g, data.Value + type);
		},
		// 频次
		'frequency': function(data)
		{
			data = data || {};
			var tpl = RENDER_TPL.frequency;
			var type_map = {
				'1': LANG('推广组'),
				'3': LANG('创意包')
			};

			var period_map = {
				'1': LANG('每小时'),
				'2': LANG('每天'),
				'0': LANG('每周'),
				'3': LANG('每月'),
				'4': LANG('每半年')
			}

			var ret = '';
			var status = data.status;
			var frequency = data.frequency
			if ((status == 1) && frequency && frequency.length)
			{
				util.each(frequency, function(item)
				{
					ret += tpl.replace(/{type}/g, type_map[item.Type])
								.replace(/{period}/g, period_map[item.Period])
								.replace(/{frequency}/g, item.Frequency);
				});
			}
			else
			{
				ret = '<div class="pd10">不限</div>';
			}

			return ret;
		},
		// 特殊条件
		'special_condition': function(data)
		{
			data = data || [];
			var tpl = RENDER_TPL.special_condition;
			var def = LANG('点击设置');
			if (data.length)
			{
				return tpl.replace(/{number}/, data.length);
			}
			// 默认状态
			else
			{
				return '<div class="pd5 lh30 text-muted">'+ LANG('点击设置') + '</div>';
			}
		},
		// 创意包落地页
		'materialGroup': function(data)
		{
			data = data || [];
			var tpl = RENDER_TPL.materialGroup;
			if (data.length)
			{
				var str = '';
				var sweetyIds = [];
				var whiskyIds = [];

				// 去重
				util.each(data, function(item)
				{
					// 创意包
					util.each(item.Sweety, function(sweety)
					{
						if (sweetyIds.indexOf(sweety._id) == -1)
						{
							sweetyIds.push(sweety._id);
						}
					});
					// 落地页
					util.each(item.Whisky, function(whisky)
					{
						if (whiskyIds.indexOf(whisky._id) == -1)
						{
							whiskyIds.push(whisky._id);
						}
					});
				});

				str += tpl.replace(/{sweety_number}/, sweetyIds.length)
								.replace(/{whisky_number}/, whiskyIds.length);
				return str;
			}
			else
			{
				return '<div class="pd5 lh30 text-muted">'+ LANG('点击设置') + '</div>';
			}
		},
		'optimizeStrategy': function(data)
		{
			data = data || {};
			var tpl = RENDER_TPL.optimizeStrategy;
			var common_map = {
				'0': LANG('智能优化'),
				'1': LANG('按点击优化'),
				'2': LANG('按注册优化'),
				'3': LANG('人工分配')
			};
			var impression_map = {
				'0': LANG('随机'),
				'1': LANG('循环'),
				'2': LANG('轮显')
			};

			return tpl.replace(/{sweety}/, common_map[data.SweetyOptimizeType || 0])
						.replace(/{whisky}/, common_map[data.WhiskyOptimizeType || 0])
						.replace(/{spot}/, common_map[data.SpotOptimizeType || 0])
						.replace(/{impression}/, impression_map[data.ImpressionOptimizeType || 0]);
		},
		'condition': function(data) {
			var desc = data.Desc;
			if(desc.length > 200){
				desc = desc.slice(0, 200) + '...';
			}

			return RENDER_TPL.condition.replace(/{desc}/g, desc).replace(/{title}/g, desc);
		}

	};
	exports.RENDER_FUNC = RENDER_FUNC;

	// 处理数据
	var PROCESS_DATA = {
		'budget': function(budget)
		{
			// 预算
			// var totalLimit = (budget && budget.totalLimit) || {};
			// totalLimit.Budget = +totalLimit.Budget || 0;
			// totalLimit.Impression = +totalLimit.Impression || 0;
			// totalLimit.Click = +totalLimit.Click || 0;

			// var dailyLimit = (budget && budget.dailyLimit) || {};
			// dailyLimit.Budget = +dailyLimit.Budget || 0;
			// dailyLimit.Impression = +dailyLimit.Impression || 0;
			// dailyLimit.Click = +dailyLimit.Click || 0;
			
			// 转成和计划的预算控制一样的数据结构发送，保存数据，方便后端处理数据
			var totalLimit = (budget && budget.totalLimit) || {};
			var dailyLimit = (budget && budget.dailyLimit) || {};
			
			var totalTmp = [];
			var dailyTmp = [];
			util.each(totalLimit, function(value, key)
			{
				totalTmp.push({'field': key, 'value': +value || 0});
			});
			util.each(dailyLimit, function(value, key)
			{
				dailyTmp.push({'field': key, 'value': +value || 0});
			});

			return {
				'dailyLimit': dailyTmp,
				'totalLimit': totalTmp
			}
		},
		'frequency': function(frequency)
		{
			frequency = frequency || [];
			var ret = [];
			util.each(frequency, function(item)
			{
				item = item || {};
				var tmp = {};
				tmp.Frequency = +item.Frequency || 0;
				tmp.Period = +item.Period || 1;
				tmp.Type = +item.Type || 1;
				ret.push(tmp);
			});
			return ret;
		},
		'extra': function(extra, self)
		{
			extra = extra || [];
			var ret = [];

			util.each(extra, function(item)
			{
				item = item || {};
				var tmp = {};
				//条件选择部分
				tmp.Condition = item.condition;


				tmp.Strategy = {};
				// 差异出价
				var bid = item.extra_price || {};
				bid.Type = +bid.Type || 1;
				bid.Value = +bid.Value || 0;
				tmp.Strategy.Bid = bid;

				// 预算
				var budget = PROCESS_DATA.budget(item.budget);
				tmp.Strategy.TotalLimit = budget.totalLimit;
				tmp.Strategy.DailyLimit = budget.dailyLimit;

				// 频次
				tmp.Strategy.FrequencyFilters =  PROCESS_DATA.frequency(item.frequency.frequency || []);

				// 创意包落地页
				tmp.Strategy.MaterialGroup = self.getMaterial(item.materialGroup) || [];
				// todo 策略

				tmp.Strategy.OptimizeStrategy = PROCESS_DATA.optimizeStrategy(item.optimizeStrategy || {});

				ret.push(tmp);
			});

			return ret;
		},
		'materialGroup': function (data, mod) {
			mod.reset();
			mod.setValue(data);
			return mod.getData();
		},
		'optimizeStrategy': function(data) {
			data = util.clone(data || {});
			data.SweetyOptimizeType = data.SweetyOptimizeType || 0;
			data.SweetyRatio = data.SweetyRatio || {};
			data.WhiskyOptimizeType = data.WhiskyOptimizeType || 0;
			data.WhiskyRatio = data.WhiskyRatio || {};
			data.SpotOptimizeType = data.SpotOptimizeType || 0;
			data.ImpressionOptimizeType = data.ImpressionOptimizeType || 0;
			return data;
		}
	};
	exports.PROCESS_DATA = PROCESS_DATA;

	function isEqualIds(aIds, bIds)
	{
		aIds = aIds || [];
		bIds = bIds || [];

		if (aIds.length != bIds.length)
		{
			return false;
		}

		for (var i = 0; i < aIds.length; i++)
		{
			if (bIds.indexOf(aIds[i]) == -1)
			{
				return false;
			}
		}

		return true;

	}
	exports.isEqualIds = isEqualIds;

	function formatItemsToIds(items, key)
	{
		key = key || '_id'

		var ids = [];
		util.each(items, function(item)
		{
			if (ids.indexOf(item[key]) == -1)
			{
				ids.push(item[key]);
			}
		});
		return ids;
	}

	exports.formatItemsToIds = formatItemsToIds

	function isEqualSweetyAndWhisky(oldData, newData)
	{
		var oldWhiskyIds = formatItemsToIds(oldData.whiskys || []);
		var oldSweetyIds = formatItemsToIds(oldData.sweetys || []);

		var newWhiskyIds = formatItemsToIds(newData.whiskys || []);
		var newSweetyIds = formatItemsToIds(newData.sweetys || []);

		var ret = {
			'sweety': true,
			'whisky': true
		}

		if (!this.isEqualIds(oldWhiskyIds, newWhiskyIds))
		{
			ret.whisky = false;
		}

		if (!this.isEqualIds(oldSweetyIds, newSweetyIds))
		{
			ret.sweety = false;
		}
		return ret;
	}
	exports.isEqualSweetyAndWhisky = isEqualSweetyAndWhisky;

	exports.getOptimizeStrategyData = function(optimizeStrategy, materialGroup)
	{
		optimizeStrategy = util.clone(optimizeStrategy || {});
		materialGroup = util.clone(materialGroup || []);
		var sweetyIds = [];
		var sweetys = [];
		var whiskyIds = [];
		var whiskys = [];
		// 去重
		util.each(materialGroup, function(item)
		{
			// 创意包
			util.each(item.Sweety, function(sweety)
			{
				if (sweetyIds.indexOf(sweety._id) == -1)
				{
					sweetyIds.push(sweety._id);
					sweetys.push({
						'_id': sweety._id,
						'Name': sweety.Name
					})
				}
			});
			// 落地页
			util.each(item.Whisky, function(whisky)
			{
				if (whiskyIds.indexOf(whisky._id) == -1)
				{
					whiskyIds.push(whisky._id);
					whiskys.push({
						'_id': whisky._id,
						'Name': whisky.Name
					});
				}
			});
		});

		optimizeStrategy.sweetys = sweetys;
		optimizeStrategy.whiskys = whiskys;

		return optimizeStrategy;
	}
})